/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, PickLine } from '@amcax/base';
import { ctx2, previewer } from '@app-cad/module';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useRef, useState } from 'react';
import { Vector3 } from 'three-legacy';

type FormData = {
  surface: pickedFaceData;
  reset?: boolean;
};

type Params = {
  surface: string;
  reset?: boolean;
};

function CommandInverseSurface({
  title,
  onClose,
  props,
}: CurvedCmdDialogParams) {
  const { picker } = useTools();
  const arrow = useRef<PickLine>(null);

  const [formData, setFormData] = useState<FormData>({
    surface: null,
  });

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({
        surface: null,
      });
      return;
    }

    const params: Params = props.params;
    const { surface, reset } = params;

    await initEditDependency([surface]);

    setFormData({
      surface: picker.generatePickObjByPickID(surface) as pickedFaceData,
      reset: reset || false,
    });
  }, []);

  const preview = async () => {
    previewer.clear();
    if (!isFormDataValid()) {
      return;
    }

    await execute(true);
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const execute = async (preview: boolean) => {
    const { surface, reset } = formData;

    const result = await confirmCommand(
      {
        type: 'Reverse',
        a: {
          surface: getIdOfPickedObj(surface),
          reset: reset || false,
        },
      },
      preview,
    );

    const { location, direction } = result?.Profile || {};

    if (location && direction) {
      if (arrow.current) {
        ctx2.cadScene.assisGroup.remove(arrow.current);
        arrow.current = null;
      }
      const offset = 2;
      const vector = new Vector3(direction[0], direction[1], direction[2]);
      const midPoint = new Vector3(location[0], location[1], location[2]);

      arrow.current = new PickLine({
        vertexs: [new Vector3(), vector.clone().setLength(offset)],
        showArrow: true,
        isKeepSize: true,
        keepSizeOrigin: midPoint
          .clone()
          .add(vector.setLength(offset))
          .toArray(),
        camera: ctx2.viewer.sceneSetup.oCamera,
        lineWidth: 4,
      });

      arrow.current.addTo(ctx2.cadScene.assisGroup);
      ctx2.viewer.requestRender();
    }
  };

  const isFormDataValid = () => {
    return formData.surface != null;
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-inverse-surface', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      surface: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
      reset: {
        type: 'boolean',
        title: '重置初始方向',
        default: false,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface: {
          'ui:placeholder': '请输入平面或曲面',
          'ui:autofocus': true,
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdInverseSurface: CurvedBaseCommand = {
  id: 'CommandInverseSurface',
  label: 'command.inverse-surface',
  icon: 'commands/curved/inverse-surface',
  create: (label, onClose, props) => (
    <CommandInverseSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
